﻿using System.Windows.Data;

namespace DimensionsHelper.Client.Helpers;

public static class BindingHelper
{
    public static readonly DependencyProperty DummyProperty =
        DependencyProperty.RegisterAttached(
            "Dummy",
            typeof(object),
            typeof(BindingHelper),
            new UIPropertyMetadata(null));

    public static readonly DependencyProperty DummyTextProperty =
        DependencyProperty.RegisterAttached(
            "DummyText",
            typeof(string),
            typeof(BindingHelper),
            new UIPropertyMetadata(null));


    public static object? Eval(Binding? binding, DependencyObject? d = null)
    {
        ArgumentNullException.ThrowIfNull(binding, nameof(binding));

        d ??= new DependencyObject();

        if (string.IsNullOrEmpty(binding.StringFormat))
        {
            BindingOperations.SetBinding(d, DummyProperty, binding);
            return d.GetValue(DummyProperty);
        }

        BindingOperations.SetBinding(d, DummyTextProperty, binding);
        return d.GetValue(DummyTextProperty);
    }

    public static object? Eval(object? source, string? expression, string? format)
    {
        Binding? binding = new(expression) { Source = source, StringFormat = format };
        return Eval(binding);
    }
}